﻿Public Class DirDialog

    Public WithEvents SelectedDir As TreeViewItem = Nothing

    Private Sub DirDialog_Loaded(sender As Object, e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        For Each drive As IO.DriveInfo In My.Computer.FileSystem.Drives
            Dim driveitem As New TreeViewItem
            driveitem.Header = drive.Name
            driveitem.Tag = drive.RootDirectory.FullName
            DirTreeView.Items.Add(driveitem)
            For Each Dir As String In My.Computer.FileSystem.GetDirectories(drive.RootDirectory.FullName)
                Dim dirinfo As New IO.DirectoryInfo(Dir)
                Dim subdiritem As New TreeViewItem
                subdiritem.Header = dirinfo.Name
                subdiritem.Tag = dirinfo.FullName
                driveitem.Items.Add(subdiritem)
                For Each subdir As String In My.Computer.FileSystem.GetDirectories(subdiritem.Tag)
                    Dim subdirinfo As New IO.DirectoryInfo(subdir)
                    Dim subdirtreeitem As New TreeViewItem
                    subdirtreeitem.Header = subdirinfo.Name
                    subdirtreeitem.Tag = subdirinfo.FullName
                    subdiritem.Items.Add(subdirtreeitem)
                Next
            Next
        Next
    End Sub

    Private Sub OKButton_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles OKButton.Click
        DialogResult = True
        Close()
    End Sub

    Private Sub SelectedDir_Expanded(sender As Object, e As System.Windows.RoutedEventArgs) Handles SelectedDir.Expanded
        For Each Dir As String In My.Computer.FileSystem.GetDirectories(SelectedDir.Tag)
            Dim dirinfo As New IO.DirectoryInfo(Dir)
            Dim diritem As New TreeViewItem
            diritem.Header = dirinfo.Name
            diritem.Tag = dirinfo.FullName
            SelectedDir.Items.Add(diritem)
        Next
    End Sub

    Private Sub DirTreeView_SelectedItemChanged(sender As Object, e As System.Windows.RoutedPropertyChangedEventArgs(Of Object)) Handles DirTreeView.SelectedItemChanged
        SelectedDir = DirTreeView.SelectedItem
    End Sub
End Class